<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\middleware\admin\Auth;
use app\model\ClassStudent;
use app\model\ProceedsDetails;
use think\facade\Db;
use think\Request;
use app\model\Proceeds as ProceedsModel;
use app\model\InvoiceDetails;
use app\model\Invoice;

class Proceeds extends BaseController
{
    protected $middleware=[Auth::class];
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index($limit = 10)
    {
        $name = request()->param('name');
        $status = request()->param('status');
        $time = request()->param('time');
        $school = request()->param('school_id');
        $student_id = request()->param('student_id');
        $data = ProceedsModel::with(['paytype','school','admin'])->where('school_id', $school)->when($name, function ($query) use ($name) {
            $query->where('student_name', 'like', "%$name%");
        })->when($status, function ($query) use ($status) {
            $query->where('status', $status);
        })->when($time, function ($query) use ($time) {
            $query->whereBetween('create_time', $time);
        })   ->when($student_id, function ($query) use ($student_id) {
            $query->where('student_id', $student_id);

        })->order('id', 'desc')->paginate($limit)->toArray();

        foreach ($data['data'] as &$item) {

            $item['product']= ProceedsDetails::with('invoice.bh')->where('proceeds_id', $item['id'])
                ->alias('pd')
                ->join('invoice_details ind', 'pd.invoice_details_id = ind.id', 'left')
                ->where('ind.type', 1)
                ->select();
            $item['products_group'] = ProceedsDetails::with('invoice.bh')->where('proceeds_id', $item['id'])
                ->alias('pd')
                ->join('invoice_details ind', 'pd.invoice_details_id = ind.id', 'left')
                ->where('ind.type', 2)
                ->select();
            $item['course'] = ProceedsDetails::with('invoice.bh')->where('proceeds_id', $item['id'])
                ->alias('pd')
                ->join('invoice_details ind', 'pd.invoice_details_id = ind.id', 'left')
                ->where('ind.type', 3)
                ->select();
            $item['ticket'] = ProceedsDetails::with('invoice.bh')->where('proceeds_id', $item['id'])
                ->alias('pd')
                ->join('invoice_details ind', 'pd.invoice_details_id = ind.id', 'left')
                ->where('ind.type', 4)
                ->select();
            $item['totalmoney']=ProceedsDetails::where('proceeds_id', $item['id'])->sum('grandtotal');
        }
        return $this->success($data);

    }


    public function create(Request $request)
    {
        $params = $request->param();

        $model = ProceedsModel::create([
            'invoice_id'=>$params['invoice_id'],
            'student_name'=>$params['student_name'],
            'student_id'=>$params['student_id'],
            'school_id'=>$params['school_id'],
            'money'=>$params['money'],
            'payment'=>$params['payment'],
            'remark'=>$params['remark']?:'',
            'notice'=>$params['notice']?:'',
            'number'=>getNumber('收款'),
            'debt'=>$params['debt'],
            'admin_id'=>request()->userid,
            'consult'=>mt_rand(100000000,99999999999)
        ]);
        foreach ($params['data'] as $item) {
            ProceedsDetails::create([
                'proceeds_id' => $model->id,
                'invoice_details_id' => $item['invoice_details_id'],
                'money' => $item['money'],
                'debt'=>$item['debt'],
                'grandtotal'=>$item['money']
            ]);
        }

        $this->compute($model->id);

        return $this->success();
    }


    public function fastCreate(Request $request)
    {
        $params = $request->param();
        Db::startTrans();
        try {
            $inv= Invoice::create([
                'school_id'=>$params['school_id'],
                'student_id'=>$params['student_id'],
                'admin_id'=>request()->userid,
                'number'=>getNumber('發票'),
                'pay'=>2
            ]);
            foreach ($params['data'] as $item) {

                InvoiceDetails::create([
                    'invoice_id' => $inv->id,
                    'name' => $item['name'],
                    'cid' => $item['id'],
                    'num' => $item['num'],
                    'price' => $item['price'],
                    'type' => $item['type'],
                    'total_prices' => $item['total_prices'],
                    'discount_id' => $item['discount_id'],
                    'discount_price' => $item['discount_price']
                ]);
            }

            $model = ProceedsModel::create([
                'invoice_id'=>$inv->id,
                'student_name'=>$params['student_name'],
                'student_id'=>$params['student_id'],
                'school_id'=>$params['school_id'],
                'money'=>$params['money'],
                'payment'=>$params['payment'],
                'remark'=>$params['remark']?:'',
                'notice'=>$params['notice']?:'',
                'number'=>getNumber('收款'),
                'debt'=>0,
                'admin_id'=>request()->userid,
                'consult'=>mt_rand(100000000,99999999999)
            ]);
            $invs= InvoiceDetails::where('invoice_id',$inv->id)->select();
            foreach ($invs as $v){
                ProceedsDetails::create([
                    'proceeds_id' => $inv->id,
                    'invoice_details_id' => $v->id,
                    'money' => $v['total_prices'],
                    'debt'=>0,
                    'grandtotal'=>$v['total_prices']
                ]);
            }
            Db::commit();
            return $this->success();
        }catch (\Exception $e)
        {
          Db::rollback();

        }

    }

    public function update($id)
    {
        $params = request()->param();

       ProceedsModel::where('id',$id)->update([
            'invoice_id'=>$params['invoice_id'],
            'student_name'=>$params['student_name'],
            'student_id'=>$params['student_id'],
            'school_id'=>$params['school_id'],
            'payment'=>$params['payment'],
            'remark'=>$params['remark']?:'',
            'notice'=>$params['notice']?:'',
            'debt'=>$params['debt'],
            'admin_id'=>request()->userid,
        ]);
        ProceedsModel::where('id',$id)->inc('money',intval($params['money']))->update();
        foreach ($params['data'] as $item) {
            ProceedsDetails::where('invoice_details_id',$item['invoice_details_id'])->update([
                'proceeds_id' => $id,
                'invoice_details_id' => $item['invoice_details_id'],
                'money' => $item['money'],
                'debt'=>$item['debt']
            ]);

            ProceedsDetails::where('invoice_details_id',$item['invoice_details_id'])->inc('grandtotal',intval($item['money']))->update();
        }
        $this->compute($id);
        return $this->success();
    }


    public function delete($id)
    {
        ProceedsModel::where('id', 'in', $id)->delete();
        ProceedsDetails::where('proceeds_id', 'in', $id)->delete();
        return $this->success();
    }


    private function compute($id)
    {
        $proceeds = ProceedsModel::where('id', $id)->find();
        $price = Invoice::where('id',$proceeds->invoice_id)->value('price');
//        ProceedsModel::where('id', $id)->update(['money' => $sum]);
//        if (array_sum(array_column($res, 'money')) == $sum) {
//            Invoice::where('id', $invoice_id)->update(['pay' => 2]);
//        }
        if($proceeds->money==$price){
            Invoice::where('id', $proceeds->invoice_id)->update(['pay' => 2]);
        }

        $invoice= InvoiceDetails::where('invoice_id',$proceeds->invoice_id)->select()->toArray();
        $res=Invoice::where('id',$invoice[0]['invoice_id'])->find();
        foreach ($invoice as $item){
           if($res['pay']==2 ){
                ClassStudent::where('invoice_details_id',$item['id'])->where('student_id',$res['student_id'])->update(['status'=>2]);
           }
        }
    }

    public function derive($limit=15)
    {
        $time=request()->param('time');
        $school_id = request()->param('school_id');
        $status=request()->param('status');
        $student_id=request()->param('student_id');
        $payment_id=request()->param('payment_id');
        $admin_id=request()->param('admin_id');
        $data = ProceedsModel::with(['paytype','school','invoice','student'])
            ->when($status, function ($query) use ($status) {
            $query->where('status', $status);
        })->when($time, function ($query) use ($time) {
            $query->whereBetween('create_time', $time);
        })->when($student_id, function ($query) use ($student_id) {
            $query->where('student_id', $student_id);
        })->when($school_id,function ($query) use($school_id){
            $query->where('school_id',$school_id);
            })
        ->when($payment_id,function($query) use($payment_id){
            $query->where('payment',$payment_id);
        })->when($admin_id,function($query) use($admin_id){
                $query->where('admin_id',$admin_id);
            })
            ->paginate($limit)->toArray();

        return $this->success($data);
    }

    public function derivepro($limit=15)
    {
        $time=request()->param('time');
        $school_id = request()->param('school_id');
        $status=request()->param('status');
        $student_id=request()->param('student_id');
        $admin_id=request()->param('admin_id');

        $data=ProceedsDetails::alias('prd')
            ->join('proceeds pr', 'prd.proceeds_id=pr.id', 'left')
            ->join('student stu','pr.student_id=stu.id','left')
            ->join('payment py','pr.payment=py.id','left')
            ->join('school sh','sh.id=pr.school_id','left')
            ->join('invoice inv','pr.invoice_id=inv.id','left')
            ->join('invoice_details invd','invd.id=prd.invoice_details_id','left')
            ->field('prd.*,stu.name,stu.number student_number,sh.name school_name,py.name payment_name
            ,pr.number,pr.consult,inv.number invoice_number
            ,invd.type,invd.name product_name')
            ->when($time,function ($query)use($time){
                $query->whereBetween('prd.create_time', $time);
            })->when($school_id,function($query) use($school_id){
                $query->where('pr.school_id',$school_id);
            })
            ->when($status,function($query) use($status){
                $query->where('pr.status',$status);
            })
            ->when($student_id,function($query) use($student_id){
                $query->where('pr.student_id',$student_id);
            })
            ->when($admin_id,function($query) use($admin_id){
                $query->where('pr.admin_id',$admin_id);
            })->paginate($limit);
        return $this->success($data);
    }
}
